
package cz.muni.fi.pa165.hauntedhouses.service;

import cz.muni.fi.pa165.hauntedhouses.dao.AccountDAO;
import cz.muni.fi.pa165.hauntedhouses.dto.AccountDTO;
import cz.muni.fi.pa165.hauntedhouses.entity.Account;
import static cz.muni.fi.pa165.hauntedhouses.util.DTOAndDAOMapper.*;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

/**
 * A service class for Account controlling transactional behaviour.
 * 
 * @author Siliarus, Jan Vyhnánek, Jarda Benda
 */
@Service
@Transactional
public class SecurityServiceImpl implements SecurityService {

    @Autowired
    private AccountDAO accountDAO;

    public void setAccountDAO(AccountDAO dao) {
        this.accountDAO = dao;
    }    

    @Override
    public AccountDTO login(String username, String password) {
        if (username==null || password==null){
            throw new IllegalArgumentException ("Null argunet");
        }
        
        if (username.isEmpty() || password.isEmpty()){
            throw new IllegalArgumentException ("Empty argument");
        }
        
        Account account = accountDAO.findByUsername(username);
        if(account != null && account.getPassword().equals(password)) {
            return AccountEntityToDTOAccount(account);
        }
        return null;        
    }

    @Override
    public AccountDTO register(AccountDTO acc) {
        if(acc==null || acc.getIsAdmin()==null || acc.getPassword()==null || acc.getUsername()==null){
            throw new IllegalArgumentException("Null argument");
        }
        
        if(acc.getUsername().isEmpty() || acc.getPassword().isEmpty()){
            throw new IllegalArgumentException("Empty argument");
        }
        
        Account account = accountDAO.findByUsername(acc.getUsername());
        if(account != null){
            return null;
        } else {
            accountDAO.create(DTOAccountToEntityAccount(acc));
            account = accountDAO.findByUsername(acc.getUsername());
            return (AccountEntityToDTOAccount(account));
        }
    }
    
}
